package com.appkubes.portal.admin.facility.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 获取spring容器，以访问容器中定义的其他bean
 * 
 * @author chenxw
 *
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

	private static final Logger log = LoggerFactory.getLogger(SpringContextUtil.class);

	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) {
		SpringContextUtil.applicationContext = applicationContext;
	}

	/**
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取对象 这里重写了bean方法，起主要作用
	 * 
	 * @param name
	 * @return Object 一个以所给名字注册的bean的实例
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		Object bean = null;
		if (applicationContext == null) {
			try {
				// 如果是applicationContext为空，说明容器未启动完毕，先sleep30秒避免出问题
				Thread.sleep(10000);
				bean = applicationContext.getBean(name);
			} catch (Exception e) {
				log.error("", e);
			}
		} else {
			bean = applicationContext.getBean(name);
		}
		return bean;
	}

	/**
	 * 获取类型为requiredType的对象
	 *
	 * @param clz
	 * @return
	 * @throws org.springframework.beans.BeansException
	 */
	public static <T> T getBean(Class<T> clz) throws BeansException {
		if (applicationContext == null) {
			return null;
		}
		return (T) applicationContext.getBean(clz);
	}

	public static <T> Map<String, T> getBeans(Class<T> clz) throws BeansException {
		if (applicationContext == null) {
			return null;
		}
		return applicationContext.getBeansOfType(clz, false, false);
	}

	public static String getSpringPropertyValue(String key) {
		// Environment e = applicationContext.getEnvironment();
		return applicationContext.getEnvironment().getProperty(key);
	}

}
